import React, {ComponentType} from "react";
import {ErrorBoundary} from "@/components";
import {Spin} from "@/components/wocloud-antd";

/**
 * 异步加载组件
 * @param {*} importComponent
 */
export function asyncComponent1(importComponent: Function) {
  return class AsyncComponent extends React.Component<{}, {component: React.ReactNode}> {
    constructor(props: any) {
      super(props);
      this.state = {
        component: null
      }
    }
    async componentDidMount() {
      let { default: component} = await importComponent()
      this.setState({ component })
    }
    render() {
      const C: any = this.state.component;
      return C? <C { ...this.props } />: null
    }
  }
}

export default function asyncComponent(AsyncCom: () => Promise<{ default: ComponentType<any>; }>) {
  const Com = React.lazy(AsyncCom);

  return (props: any) => (
    <ErrorBoundary type={'chart'}>
      <React.Suspense fallback={<Spin/>}>
        <Com {...props} />
      </React.Suspense>
    </ErrorBoundary>
  );
}
